package com.lingkang.flychat.http;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.lingkang.flychat.config.UrlConfig;
import com.orhanobut.hawk.Hawk;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpUtils {

    private static Retrofit retrofit;

    private static final String BASE_URL = UrlConfig.baseServer;

    public static <T> T createApi(Class<T> tClass) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit.create(tClass);
    }

    private static OkHttpClient okHttpClient() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new LoggingInterceptor())
                .build();
        return okHttpClient;
    }

    static class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request request;
            String token = Hawk.get("token");
            if (StringUtils.isEmpty(token)) {
                request = chain.request();
            } else {
                request = chain.request().newBuilder().addHeader("token", token).build();
            }
            /*long t1 = System.nanoTime();
            Log.i("request", String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));*/
            Response response = null;
            try {
                response = chain.proceed(request);
            } catch (IOException e) {
                try {
                    response = chain.proceed(request);
                } catch (IOException ex) {
                    try {
                        response = chain.proceed(request);
                    } catch (IOException exc) {
                        throw new IOException("网络不可达");
                    }
                }
            }
            //重新取一次，因为上面用过一次了 流被关闭了
//            response = chain.proceed(request);
            return response;
        }
    }


    public static <T> void request(Observable<T> observable, final ResponseListenter<T> responseListenter) {
        observable.subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<T>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull T t) {
                        if (responseListenter != null)
                            responseListenter.onSuccess(t);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (responseListenter != null)
                            responseListenter.onFail(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
